import { useCallback, useEffect, useRef, useState } from 'react'
import { useLocation, useNavigate, useParams } from 'react-router-dom'
import { Image, Toast, Button, Space, Popup, ImageUploader, Collapse, Modal, Tag, ImageViewer, Switch } from 'antd-mobile'
import { merchantDetail, merchantImages, uploadFileMerchant, delMerchantImage, merchantDel, checkDel, exportWord, checkRectifySave } from '@api'
import { uploadFileToOSS } from '@utils/upload'
import useFileDownloader from '@hooks/useFileDownloader'
import axios from 'axios'

import './index.scss'

const tab = ['检查列表', '图片列表']
const maxCount = 9

const Meeting = () => {
    const navigate = useNavigate()
    const location = useLocation()
    const { shopId } = useParams()

    const imagesList = useRef()

    const [tabIndex, setTabIndex] = useState(0)

    const [visible, setVisible] = useState(false)

    const [fileList, setFileList] = useState([])

    const [details, setDetails] = useState({})

    const [images, setImages] = useState([])

    const [visible2, setVisible2] = useState(false)

    const [list, setList] = useState([])

    const [isSelect, setIsSelect] = useState(false)
    const [selectList, setSelectList] = useState([])

    const { downloadFile } = useFileDownloader()

    const [level, setLevel] = useState(null)

    const [desc, setDesc] = useState('')

    const [showWatermark, setShowWatermark] = useState(false)

    const [watermark, setWatermark] = useState('')

    const [visible1, setVisible1] = useState(false)

    const [violationsIds, setViolationsIds] = useState(null)

    useEffect(() => {
        getData()
        const obj = JSON.parse(localStorage.getItem('userInfo') || '{}')
        setLevel(obj.level)
    }, [])

    const getData = useCallback(() => {
        merchantDetail({ id: shopId }).then(({ success, data }) => {
            if (success) {
                setDetails(data)
                localStorage.setItem('merchantDetail', JSON.stringify(data))
            }
        })
    }, [shopId])

    // 图片列表
    const getImages = useCallback(() => {
        merchantImages({ merchantId: shopId }).then(({ success, data, info }) => {
            if (success) {
                setImages(data)
            } else {
                Toast.show(info)
            }
        })
    }, [shopId])

    useEffect(() => {
        tabIndex === 1 && getImages()
    }, [tabIndex, getImages])

    // 添加
    const add = useCallback(() => {
        if (tabIndex) {
            setVisible(true)
        } else {
            navigate(`${location.pathname}/add`)
        }
    }, [tabIndex, setVisible, location, navigate])

    // 重置
    const reset = () => {
        setVisible(false)
        setVisible1(false)
        setFileList([])
        setDesc('')
    }

    // 获取class名
    const getClassName = (text) => {
        const colorMap = {
            IN_RECTIFY: '#ffc107',
            NOT_RECTIFY: '#dc3545',
            PASS: '#28a745',
            HAVING_RECTIFY: '#28a745'
        }
        return colorMap[text] || ''
    }

    // 上传
    const upload = async (file) => {
        const { res } = await uploadFileToOSS({ file })
        try {
            return { url: res.requestUrls[0].split('?')[0] }
        } catch (error) {
            throw new Error(error)
        }
    }

    // 上传图片
    const uploadFun = () => {
        if (fileList?.length) {
            uploadFileMerchant({ images: fileList.map((e) => e.url), merchantId: shopId }).then(({ success, info }) => {
                Toast.show(info)
                if (success) {
                    getImages()
                    reset()
                }
            })
        } else {
            Toast.show('请先选择图片')
        }
    }

    // 删除图片
    const delImage = () => {
        if (selectList.length) {
            Modal.confirm({
                title: '确认操作',
                content: '您确定要批量删除图片吗？',
                confirmText: '确认',
                cancelText: '取消',
                onConfirm: () => {
                    const ids = selectList.map((e) => e.id)
                    delMerchantImage(ids).then(({ success, info }) => {
                        Toast.show(info)
                        if (success) {
                            setIsSelect(false)
                            setSelectList([])
                            getImages()
                        }
                    })
                }
            })
        } else {
            Toast.show('至少选择一张图片~')
        }
    }

    // 编辑
    const edit = (item) => {
        localStorage.setItem('checkItem', JSON.stringify(item))
        navigate(`${location.pathname}/edit`)
    }

    // 整改
    const rectification = (item) => {
        localStorage.setItem('checkItem', JSON.stringify(item))
        navigate(`${location.pathname}/rectification`)
    }

    // 编辑商户
    const editShop = () => {
        navigate(`${location.pathname}/editMerchant`)
    }

    // 删除商户
    const delShop = () => {
        Modal.confirm({
            title: '确认操作',
            content: '您确定要删除这个商户吗？',
            confirmText: '确认',
            cancelText: '取消',
            onConfirm: () => {
                merchantDel(shopId).then(({ success, info }) => {
                    Toast.show(info)
                    if (success) {
                        navigate(-1)
                    }
                })
            }
        })
    }

    // 删除检查记录
    const delCheck = (id) => {
        Modal.confirm({
            title: '确认操作',
            content: '您确定要删除这条检查记录吗？',
            confirmText: '确认',
            cancelText: '取消',
            onConfirm: () => {
                checkDel(id).then(({ success, info }) => {
                    Toast.show(info)
                    if (success) {
                        getData()
                    }
                })
            }
        })
    }

    // 导出
    const ExportToWord = (item) => {
        Toast.show({
            content: '正在导出~',
            icon: 'loading',
            duration: 0,
            maskClickable: false
        })
        let params = { keyword: '', current: 1, size: 10, checkTimeStart: '', checkTimeEnd: '', verifyId: item.id }

        try {
            exportWord(params).then(({ success, data, info }) => {
                Toast.clear()
                if (success && data) {
                    downloadFile(data)
                } else {
                    Toast.show({
                        icon: 'fail',
                        content: info
                    })
                }
            })
        } catch (err) {
            console.error('Error fetching file URL:', err)
        }
    }

    // 多选/取消多选
    const selectChange = () => {
        setSelectList([])
        setIsSelect(!isSelect)
    }

    const selectFun = (imageObj) => {
        setSelectList((prevArr) => {
            const imageIndex = prevArr.findIndex((img) => img.id === imageObj.id)
            if (imageIndex !== -1) {
                return prevArr.filter((currentImage) => currentImage.id !== imageObj.id)
            } else {
                return [...prevArr, imageObj]
            }
        })
    }

    // 批量下载
    const batchDownload = async () => {
        if (selectList.length) {
            for (const { image } of selectList) {
                try {
                    const response = await axios.get(image, {
                        responseType: 'blob' // 设置响应类型为 blob，以便处理二进制文件
                    })

                    // 创建一个临时链接元素，设置 href 为 blob URL，并模拟点击以启动下载
                    const link = document.createElement('a')
                    link.href = window.URL.createObjectURL(new Blob([response.data]))
                    link.setAttribute('download', image.split('/').pop()) // 设置下载文件名为 URL 的最后一部分
                    document.body.appendChild(link)
                    link.click()
                    link.parentNode.removeChild(link) // 下载后从 DOM 中移除该元素
                } catch (error) {
                    console.error('下载图片失败:', error)
                }
            }
        } else {
            Toast.show('请先选择图片')
        }
    }

    const addViolations = () => {
        let params = {
            verifyId: violationsIds[0],
            status: 'HAVING_RECTIFY',
            records: [ { imageList: fileList.map((e) => e.url), title: desc } ],
            verifyRecordId: violationsIds[1]
        }
        checkRectifySave(params).then(({ success, info }) => {
            Toast.show(info)
            if (success) {
                reset()
                getData()
            }
        })
    }

    return (
        <div className="ShopDetails">
            <Image fit="cover" className="details_logo" src={details.image} />
            <div className="ShopDetails_info">
                <p>
                    单位：<span>{details.unit}</span>
                </p>
                <p>
                    负责人：<span>{details.headName}</span>
                </p>
                <p>
                    电话：<span>{details.headPhone}</span>
                </p>
                <p>
                    行业类型：<span>{details.trade}</span>
                </p>
                <p>
                    单位地址：
                    <span>
                        {details.province}
                        {details.city}
                        {details.area}
                        {details.village}
                        {details.street}
                        {details.address}
                    </span>
                </p>
                {level === 0 || level === 1 ? (
                    <div className="ShopDetails_info_btns">
                        <Button color="primary" size="mini" onClick={editShop}>
                            编辑商户
                        </Button>
                        <Button color="danger" size="mini" onClick={delShop}>
                            删除商户
                        </Button>
                    </div>
                ) : null}
            </div>
            <div className="tab_box">
                <div>
                    {tab.map((e, i) => (
                        <p className={tabIndex === i ? 'active' : ''} key={i} onClick={() => setTabIndex(i)}>
                            {e}
                        </p>
                    ))}
                    <span className={tabIndex ? 'active' : ''}></span>
                </div>
                {tabIndex ? (
                    <div>
                        <Button color="primary" size="mini" onClick={selectChange}>
                            {isSelect ? '取消' : ''}多选
                        </Button>
                        <Button color="primary" size="mini" onClick={batchDownload}>
                            批量下载
                        </Button>
                        {level !== 3 ? (
                            <Button color="danger" size="mini" onClick={delImage}>
                                批量删除
                            </Button>
                        ) : null}
                    </div>
                ) : null}
            </div>
            {tabIndex ? (
                <div className="ShopDetails_images">
                    {images.map((item, index) => (
                        <div key={index}>
                            <div className="ShopDetails_images_head">
                                <p>{item.uploadTime}</p>
                            </div>
                            <Space wrap justify="start">
                                {item.images.map((ee, ii) => (
                                    <div className="ShopDetails_images_box" key={ee.id}>
                                        {isSelect ? (
                                            <div className="ShopDetails_images_mask" onClick={() => selectFun(ee)}>
                                                <span className={selectList.some((img) => img.id === ee.id) ? 'active' : ''}></span>
                                            </div>
                                        ) : null}
                                        <Image
                                            onClick={() => {
                                                imagesList?.current.swipeTo(ii)
                                                setList(item.images.map((e) => e.image))
                                                setVisible2(true)
                                            }}
                                            width={110}
                                            fit="cover"
                                            src={ee.image}
                                        />
                                    </div>
                                ))}
                            </Space>
                        </div>
                    ))}
                </div>
            ) : (
                <div className="ShopDetails_list">
                    <Collapse accordion>
                        {details.verifyList
                            ? details.verifyList.map((item) => (
                                  <Collapse.Panel
                                      key={item.id}
                                      title={
                                          <div className="ShopDetails_item">
                                              <Tag color={getClassName(item.status)}>{item.statusName}</Tag>
                                              <p>{item.checkTypeName}</p>
                                              <p>{item.checkTime}</p>
                                          </div>
                                      }
                                  >
                                      <div>
                                          {level !== 3 ? (
                                              <Button onClick={() => edit(item)} className="ShopDetails_item_btn" color="primary" size="mini">
                                                  编辑
                                              </Button>
                                          ) : null}
                                          <Button className="ShopDetails_item_btn" color="primary" size="mini" onClick={() => ExportToWord(item)}>
                                              导出
                                          </Button>
                                          {/* {item.status === 'IN_RECTIFY' ? (
                                              <Button className="ShopDetails_item_btn" color="warning" size="mini" onClick={() => rectification(item)}>
                                                  整改
                                              </Button>
                                          ) : null} */}

                                          {level !== 3 ? (
                                              <Button onClick={() => delCheck(item.id)} color="danger" className="ShopDetails_item_btn" size="mini">
                                                  删除
                                              </Button>
                                          ) : null}
                                          <Space direction="vertical">
                                              <p className="ShopDetails_list_p">
                                                  时间：<span>{item.checkTime}</span>
                                              </p>
                                              <p className="ShopDetails_list_p">
                                                  单位：<span>{details.unit}</span>
                                              </p>
                                              <p className="ShopDetails_list_p">
                                                  负责人姓名：<span>{details.headName}</span>
                                              </p>
                                              <p className="ShopDetails_list_p">
                                                  电话：<span>{details.headPhone}</span>
                                              </p>
                                              <p className="ShopDetails_list_p">
                                                  单位地址：
                                                  <span>
                                                      {details.province}
                                                      {details.city}
                                                      {details.area}
                                                      {details.village}
                                                      {details.street}
                                                      {details.address}
                                                  </span>
                                              </p>
                                              <p className="ShopDetails_list_p">
                                                  行业类型：<span>{details.trade}</span>
                                              </p>
                                              <p className="ShopDetails_list_p">
                                                  检查类型：<span>{item.checkTypeName}</span>
                                              </p>
                                              <div className="ShopDetails_list_p">
                                                  <p>检查人员（签名）：</p>
                                                  <Image src={item.inspectorsSign} fit="contain" width={120} height={40} />
                                              </div>
                                              <div className="ShopDetails_list_p">
                                                  <p>被检查单位负责人（签名）：</p>
                                                  <Image src={item.inspectedSign} fit="contain" width={120} height={40} />
                                              </div>
                                              <p className="ShopDetails_list_p">
                                                  限时整改时间：<span>{`${item.rectifyDay}天` || '无'}</span>
                                              </p>
                                              <p className="ShopDetails_list_p">经查，存在以下问题：</p>
                                              {item?.rectifyRecords?.length ? <p className="ShopDetails_list_p">整改前：</p> : null}
                                              {item?.records?.length ? (
                                                  item.records.map((ee, ii) => (
                                                      <div key={ii}>
                                                          <p className="ShopDetails_list_p" style={{ fontWeight: '400', marginBottom: '10px' }}>
                                                              { !item.rectifyRecords.find(e => e.verifyRecordId === ee.id) ? <Button color="warning" size="mini" style={{ marginRight: '10px' }} onClick={() => {
                                                                setViolationsIds([item.id, ee.id])
                                                                setVisible1(true)
                                                            }}>整改</Button> : null}
                                                              {ii + 1}.{ee.title}
                                                          </p>
                                                          <Space wrap>
                                                              {ee.imageList.map((e, i) => (
                                                                  <Image src={e} width={100} height={100} fit="cover" key={i} />
                                                              ))}
                                                          </Space>
                                                      </div>
                                                  ))
                                              ) : (
                                                  <p className="ShopDetails_list_p">无</p>
                                              )}
                                              {item?.rectifyRecords?.length ? <p className="ShopDetails_list_p">整改后：</p> : null}
                                              {item?.rectifyRecords?.length
                                                  ? item.rectifyRecords.map((ee, ii) => (
                                                        <div key={ii}>
                                                            <p className="ShopDetails_list_p" style={{ fontWeight: '400', marginBottom: '10px' }}>
                                                                {ii + 1}.{ee.title}
                                                            </p>
                                                            <Space wrap>
                                                                {ee.imageList.map((e, i) => (
                                                                    <Image src={e} width={100} height={100} fit="cover" key={i} />
                                                                ))}
                                                            </Space>
                                                        </div>
                                                    ))
                                                  : null}
                                          </Space>
                                      </div>
                                  </Collapse.Panel>
                              ))
                            : null}
                    </Collapse>
                </div>
            )}
            <div className="ShopDetails_btn">
                <Button onClick={add} color="primary">
                    {!tabIndex ? '添加检查记录' : '添加图片'}
                </Button>
            </div>
            <Popup visible={visible} onMaskClick={reset} onClose={reset} bodyStyle={{ height: '60vh' }}>
                <div className="upload_images">
                    <ImageUploader
                        style={{ '--cell-size': '110px' }}
                        value={fileList}
                        multiple
                        upload={upload}
                        maxCount={maxCount}
                        showUpload={fileList.length < maxCount}
                        onChange={setFileList}
                        onCountExceed={(exceed) => {
                            Toast.show(`最多选择 ${maxCount} 张图片，你多选了 ${exceed} 张`)
                        }}
                    />
                    <Button color="primary" onClick={uploadFun}>
                        上传图片
                    </Button>
                </div>
            </Popup>
            {/* 添加整改记录 */}
            <Popup visible={visible1} onMaskClick={reset} onClose={reset} bodyStyle={{ height: '70vh' }}>
                <div className="Add_upload_images">
                    <p>问题描述：</p>
                    <input value={desc} onChange={(e) => setDesc(e.target.value)} className="desc_inp" type="text" placeholder="请输入问题描述" />
                    <p>是否加水印：</p>
                    <Switch value={showWatermark} onChange={setShowWatermark} />
                    {showWatermark ? (
                        <>
                            <p>水印文案：</p>
                            <input value={watermark} onChange={(e) => setWatermark(e.target.value)} className="desc_inp" type="text" placeholder="请输入" />
                        </>
                    ) : null}
                    <p>问题图片：</p>
                    <ImageUploader
                        style={{ '--cell-size': '110px' }}
                        value={fileList}
                        multiple
                        upload={upload}
                        maxCount={maxCount}
                        showUpload={fileList.length < maxCount}
                        onChange={setFileList}
                        onCountExceed={(exceed) => {
                            Toast.show(`最多选择 ${maxCount} 张图片，你多选了 ${exceed} 张`)
                        }}
                    />
                    <Button color="primary" onClick={addViolations}>
                        保存
                    </Button>
                </div>
            </Popup>
            <ImageViewer.Multi
                ref={imagesList}
                images={list}
                visible={visible2}
                defaultIndex={1}
                onClose={() => {
                    setVisible2(false)
                }}
            />
        </div>
    )
}
export default Meeting
